/**
*		@file VarTable.cpp
*		@brief VarTable class
*
*		@author Zhou Nan
*
*		@date 1/25/2012
*/
#include "VarTable.h"

vector<VarEntry*>	VarTable::vp_var_entries_;


// step1: check duplication
// step2: add var
VarIdx VarTable::InsertVar(VarName var_name)
{
	// check duplication
	VarEntry* p_var_entry_temp = NULL;
	if( CheckVarNameExistence(var_name, &p_var_entry_temp) )
		return p_var_entry_temp->var_idx;

	// add var
	p_var_entry_temp = new VarEntry;
	p_var_entry_temp->var_idx = vp_var_entries_.size()+1;
	p_var_entry_temp->var_name = var_name;

	vp_var_entries_.push_back(p_var_entry_temp);
	return p_var_entry_temp->var_idx;
}

VarIdx VarTable::GetVarIdx(VarName var_name)
{
	VarEntry* p_var_entry_temp = NULL;
	if( CheckVarNameExistence(var_name, &p_var_entry_temp) )
		return p_var_entry_temp->var_idx;
	return -1;
}
	
VarName VarTable::GetVarName(VarIdx var_idx)
{
	return GetVarEntry(var_idx)->var_name;
}

bool VarTable::CheckVarNameExistence(VarName var_name, VarEntry** pp_var_entry)
{
	vector<VarEntry*>::iterator iter_p_var_entry;
	for( iter_p_var_entry = vp_var_entries_.begin();
		iter_p_var_entry != vp_var_entries_.end();
		iter_p_var_entry++ )
	{
		if( (*iter_p_var_entry)->var_name.compare(var_name) == 0 )
		{
			*pp_var_entry = *iter_p_var_entry;
			return true;
		}
	}
	return false;
}

VarEntry*	VarTable::GetVarEntry(VarIdx proc_idx)
{
	return vp_var_entries_[proc_idx-1];
}

string VarTable::ToString()
{
	stringstream ss_result;
	ss_result << "VarTable :\n";
	vector<VarEntry*>::iterator iter_p_var_entry;
	for(iter_p_var_entry = vp_var_entries_.begin();
		iter_p_var_entry != vp_var_entries_.end();
		iter_p_var_entry++)
	{
		ss_result <<  ((*iter_p_var_entry)->var_idx) << " : " << ((*iter_p_var_entry)->var_name) << endl;
	}
	return ss_result.str();
}
